package it.rap.applications.persistence;

import it.rap.application.logic.mappers.MovimentoLogic;
import it.rap.applications.persistence.entities.test.Job;
import it.rap.applications.persistence.entities.test.Publisher;

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {
	private EntityManagerFactory emf;
	 
	@SuppressWarnings("unchecked")
	public Object start(IApplicationContext context) throws Exception {
		MovimentoLogic mLogic = new MovimentoLogic();
		/*
		mLogic.openTransaction();
		Movimento mov = new Movimento();
		mov.setDataContabile(new SimpleDateFormat("ddMMyyyy").parse("04012013")  );
		Double d =  Math.random();
		mov.setAccredito( d.floatValue() );
		mov.setDescrizione("mov 1");
		mov.setDescrizioneCompleta("mov 1");
		
		mLogic.insert(mov);
		
		Movimento mov2 = new Movimento();
		mov2.setDataContabile( new SimpleDateFormat("ddMMyyyy").parse("05012013") );
		Double d =  Math.random();
		mov2.setAccredito( d.floatValue() );
		mov2.setDescrizione("mov 2");
		mov2.setDescrizioneCompleta("mov 2");
		
		mLogic.insert(mov2);
		
		mLogic.commit();		
		
		Movimento m = mLogic.loadMovimentoMaxDataContabile();
		
		List<Movimento> mList = mLogic.selectAll(0, 100);
		
		Saldo s = mLogic.calcolaSaldo();
		
		Movimento mov2 = new Movimento();
		mov2.setDataContabile( new SimpleDateFormat("ddMMyyyy").parse("01012013") );
		mov2.setAccredito( (float) 0.260237 );
		mov2.setDescrizione("mov 1");
//		mov2.setDescrizioneCompleta("mov 1");
		int esiste = mLogic.esisteMovimento( mov2 );
		
		System.out.println(" $$$$ ");
		/*
		
		Movimento m = new Movimento();
		m.setDataContabile(new Date() );
		m.setAccredito( (float) 23425 );
		
		mLogic.insert(m);
		
		List<Movimento> mList = mLogic.selectAll(0, 100);
		
		System.out.println(" $$$$ ");
		*/
		
		emf = Persistence.createEntityManagerFactory("publisher");
		EntityManager em = emf.createEntityManager();
		
		Publisher p = new Publisher();
		p.setName("ELEMENT_"+Math.random());
		p.setCost(new BigDecimal( Math.random() ));
		p.setPublischer("PUBLISCHER NUMBER:"+Math.random());
		
		em.getTransaction().begin();
		
		Job j = new Job();
		j.setJobDescr("Lavoco"+Math.random());
		j.setJobDescr(""+Math.random());
		
		p.getJobList().add(j);
		em.persist(j);
		em.persist(p);
		em.getTransaction().commit();
		
		Query query = em.createQuery("Select p from Publisher p order by p.name asc");		
		List<Publisher> publishers = query.getResultList();
		for (Publisher publisher : publishers) {
			System.out.println(publisher.toString());
		}
		
		em.close();
		
		return EXIT_OK;
	}
 
	public void stop() {
		emf.close();
	}
}
